<?php

namespace App\Admin\Actions\Post;

use App\Model\Guild\GuildManage;
use App\Model\Guild\GuildWithdrawal;
use App\Model\Message;
use App\Model\User;
use Encore\Admin\Actions\BatchAction;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UpdateGuildWithdrawOkXmi extends BatchAction
{
    public $name = "<a class='report-postsxmi btn btn-sm btn-info'><i class='fa fa-info-circle'></i>芯米云账户提现</a>";
    protected $selector = '.report-postsxmi';


    public function handle(Collection $collection,Request $request){
        $ids = $request->input('_key');

        $ids = is_array($ids) ? $ids :  explode(',', $ids);

        if(count($ids)<=0){
            return $this->response()->error('请选择要操作的ID')->refresh();
        }
        if(count($ids)>20){
            return $this->response()->error('一次最多只能选择20个哦！')->refresh();
        }

        $ret = ['ret' => 0, 'message' => '操作成功！'];
        $uidCount = 0;
        $logId = [];
        $payWay = request('extra',GuildWithdrawal::XIN_MI_SUBJECT);
        foreach ($ids as $key => $val){
            $id = $val;

            $record = GuildWithdrawal::find($id);
            //记录不存在
            if (!$record) {
                DB::commit();
                continue;
            }

            $guild = GuildManage::getInfoByUserId($record->user_id);
            //判断推广员状态
            if (empty($guild) || $guild->status != 1){
                $uidCount = $uidCount+1;
                continue;
            }

            //状态不等于审核状态不给与操作
            if ($record->status != GuildWithdrawal::STATUS_ING) {
                $uidCount = $uidCount+1;
                $logId[] = $id;
                continue;
            }
            //判断用户状态
            $userInfo = User::find($record->user_id);
            if(empty($userInfo) || $userInfo->status != 0){
                $uidCount = $uidCount+1;
                $logId[] = $id;
                continue;
            }

            DB::beginTransaction();
            try {
                $withdrawWay = '';
                if ($payWay == GuildWithdrawal::XIN_MI_SUBJECT) {
                    $ret = GuildWithdrawal::doYzhOrder($record->toArray(),$payWay);
                    $withdrawWay = isset($ret['bind_type']) && $ret['bind_type'] == GuildWithdrawal::WITHDRAW_TYPE_ALI ? '支付宝' : '银行卡';
                    Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                }

                if ($ret['ret'] == -1){
                    $uidCount = $uidCount+1;
                }

                //提现审核已经通过
                if ($ret['ret'] == 0) {
                    $time = date('Y年m月d日', strtotime((string)$record->created_at));
                    $pushMsg = "你于{$time}申请的提现已通过审核，请注意查收你的{$withdrawWay}账号！";
                    Message::pushSystem($record->user_id, $pushMsg, '提现通知');
                    GuildWithdrawal::where('id', $id)->limit(1)->update([
                        'status' => GuildWithdrawal::STATUS_OK,
                        'withdraw_way' => $payWay
                    ]);

                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
                Log::info(__CLASS__ . "==WithdrawId:{$id}==Exception:" . $e->getMessage());
            }
        }
        $count = count($ids);
        $success = (int)$count-$uidCount;
        if($uidCount>0){
            $logIdStr = implode(',',$logId);
            $successStr = '成功条数:（'.$success.'条） 失败条数：（'.$uidCount.'条） 失败的记录ID：'.$logIdStr;
            return $this->response()->success($successStr)->refresh();
        }

        return $this->response()->success('修改成功')->refresh();
    }

    public function dialog($ids = '')
    {
        $this->confirm('确认执行该操作么？');
    }

    public function html()
    {
        return "<a class='report-postsxmi btn btn-sm btn-info'><i class='fa fa-info-circle'></i>允许提现</a>";
    }
}
